package com.zhx.common.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.zhx.common.common.constant.MQConstant;
import com.zhx.common.common.constant.RedisKey;
import com.zhx.common.common.domain.dto.LoginMessageDTO;
import com.zhx.common.common.domain.dto.ScanSuccessMessageDTO;
import com.zhx.common.common.util.MQProducer;
import com.zhx.common.user.dao.UserDao;
import com.zhx.common.user.domain.entity.User;
import com.zhx.common.user.service.IUserService;
import com.zhx.common.user.service.WXMsgService;
import com.zhx.common.user.service.adapter.TextBuilder;
import com.zhx.common.user.service.adapter.UserAdapter;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import utils.RedisUtils;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class WxMsgServiceImpl implements WXMsgService {
    /**
     * openId 和 登录code 的关系map，通过找到code进入找到与code关联的channel
     */
    private static final ConcurrentHashMap<String,Integer> WAIT_AUTHORIZE_MAP = new ConcurrentHashMap<>();

    private static final String URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

    @Value("${wx.mp.callback}")
    private String callback;

    @Resource
    private UserDao userDao;

    @Resource
    private IUserService userService;

    @Lazy
    @Resource
    private WxMpService wxMpService;

    @Resource
    private MQProducer mqProducer;


    @Override
    public WxMpXmlOutMessage scan(WxMpXmlMessage wxMpXmlMessage) {
        String openId = wxMpXmlMessage.getFromUser();
        Integer code = getEventKey(wxMpXmlMessage);

        if(Objects.isNull(code)){
            return null;
        }

        User user = userDao.getByOpenId(openId);
        boolean isRegister = Objects.nonNull(user);
        //没有头像的话说明还没有授权
        boolean isAuthorize = isRegister && StrUtil.isNotBlank(user.getAvatar());
        //用户已经注册并授权，直接登陆成功
        if(isRegister && isAuthorize){
            log.info("用户已经注册并授权，直接登陆成功");
            mqProducer.sendMsg(MQConstant.LOGIN_MSG_TOPIC, new LoginMessageDTO(user.getId(), code));
            return null;
        }

        //没有注册
        if(!isRegister){
            log.info("用户没有注册，注册用户");
            User insert = UserAdapter.builderUserSave(openId);
            userService.register(insert);
        }

        //在redis中保存openid和场景code的关系，后续才能通知到前端,旧版数据没有清除,这里设置了过期时间
        RedisUtils.set(RedisKey.getKey(RedisKey.OPEN_ID_STRING, openId), code, 60, TimeUnit.MINUTES);

        //用户扫描成功等待授权，发送消息让用户授权，type=2
        log.info("用户扫描成功等待授权,发送消息");
        mqProducer.sendMsg(MQConstant.SCAN_MSG_TOPIC, new ScanSuccessMessageDTO(code));

        //推送链接让用户登陆,点击登录后会回调,地址为当前服务器的地址
        String authorizeUrl = String.format(URL, wxMpService.getWxMpConfigStorage().getAppId(), URLEncoder.encode(callback + "/wx/portal/public/callBack"));
        System.out.println(authorizeUrl);
        //公众号返回给用户信息
        return TextBuilder.build("请点击登录：<a href=\"" + authorizeUrl + "\" >登录</a>",wxMpXmlMessage);
    }

    @Override
    public void authorize(WxOAuth2UserInfo userInfo) {
        String openid = userInfo.getOpenid();
        User user = userDao.getByOpenId(openid);
        //更新用户信息 如果头像为空说明还没有授权
        if(StrUtil.isBlank(user.getAvatar())){
            //补全用户信息
            fillUserInfo(user.getId(),userInfo);
        }
        //找到对应的code
        Integer code = RedisUtils.get(RedisKey.getKey(RedisKey.OPEN_ID_STRING, userInfo.getOpenid()), Integer.class);
        //通过code找到用户channel进行登录
        mqProducer.sendMsg(MQConstant.LOGIN_MSG_TOPIC, new LoginMessageDTO(user.getId(), code));
    }

    //补全用户信息
    private void fillUserInfo(Long id,WxOAuth2UserInfo userInfo) {
        User user = UserAdapter.buildAuthorizeUser(id, userInfo);
        try{
            userDao.updateById(user); //名称设置了唯一索引，如果重复会报下面错误
        }catch (DuplicateKeyException e){
            log.error("用户名称重复...");
            e.printStackTrace();
        }
    }


    private Integer getEventKey(WxMpXmlMessage wxMpXmlMessage){
        try{
            String eventKey = wxMpXmlMessage.getEventKey();
            String code = eventKey.replace("qrscene_","");
            return Integer.parseInt(code);
        }catch (Exception e){
            log.error("getEventError error eventKey:{}",wxMpXmlMessage.getEventKey(),e);
            return null;
        }
    }
}
